#!/bin/bash
###
 # @Author: didiplus
 # @Description: 
 # @Date: 2025-08-07 11:29:52
 # @LastEditors: didiplus
 # @LastEditTime: 2025-08-08 12:43:21
 # @FilePath: /script/StarInspect/playbook/collect_info.sh
 # @Version: 1.0
### 

# 获取主机信息
HOSTNAME=$(hostname)
IP=$(hostname -I | awk '{print $1}')
MODEL=$(sudo dmidecode -s system-product-name 2>/dev/null || echo "Permission denied")
SN=$(sudo dmidecode -s system-serial-number 2>/dev/null || echo "Permission denied")
OS=$( grep '^PRETTY_NAME=' /etc/os-release | cut -d= -f2 | tr -d '"')
KERNEL=$(uname -r)
UPTIME=$(uptime -p | sed 's/up //')
ARCH=$(uname -m)

# CPU 和 内存
CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | awk '{print 100 - $8}')
CPU_MODEL=$(lscpu | grep "Model name" | awk -F: '{print $2}' | xargs)
CPU_CORES=$(lscpu | grep "Core(s) per socket" | awk '{print $4}')
CPU_THREADS=$(lscpu | grep "Thread(s) per core" | awk '{print $4}')
MEM_TOTAL=$(free -g | awk '/Mem/ {print $2}')
MEM_USED=$(free -g | awk '/Mem/ {print $3}')
MEM_PERCENT=$(free | awk '/Mem/ {printf "%.1f", $3/$2 * 100}')
# 获取内存条信息
MEMORY_DETAILS=$(sudo dmidecode -t memory | grep -i "Size" | grep -v "No Module Installed" | awk '{print $2}' | sort | uniq -c | awk '{print $2 "GB * " $1}' | head -n 1)

# 磁盘信息
DISKS=$( df -h --output=source,used,avail,pcent,target | \
    grep "^/dev" | awk '{printf "{\"device\":\"%s\",\"used\":\"%s\",\"avail\":\"%s\",\"percent\":\"%s\",\"mount\":\"%s\"},", $1, $2, $3, $4,$5 }' | sed 's/,$//')
# 磁盘总容量
DISK_TOTAL=$(df -h --total | grep "total" | awk '{print $2}')

# 主板和BIOS信息
MOTHERBOARD=$(sudo dmidecode -s baseboard-product-name 2>/dev/null || echo "Permission denied")
BIOS_VERSION=$(sudo dmidecode -s bios-version 2>/dev/null || echo "Permission denied")

# 系统负载
# LOAD_AVG=$(cat /proc/loadavg | awk '{print "["$1","$2","$3"]"}')
LOAD_AVG=$(awk '{print "["$1","$2","$3"]"}' /proc/loadavg)

# Top 5 占用资源进程
TOP5=$(ps -eo pid,comm,%cpu,%mem --sort=-%cpu | head -n 6 | \
    awk 'NR>1 {printf "{\"pid\":%s,\"name\":\"%s\",\"cpu\":%s,\"mem\":%s},", $1, $2, $3, $4}' | sed 's/,$//')

# 输出为 JSON
echo "{
  \"name\": \"$HOSTNAME\",
  \"ip\": \"$IP\",
  \"model\": \"$MODEL\",
  \"sn\": \"$SN\",
  \"os\": \"$OS\",
  \"kernel\": \"$KERNEL\",
  \"uptime\": \"$UPTIME\",
  \"cpu\": $CPU_USAGE,
  \"cpu_model\": \"$CPU_MODEL\",
  \"cpu_cores\": $CPU_CORES,
  \"cpu_threads\": $CPU_THREADS,
  \"arch\": \"$ARCH\",
  \"memory_total\": \"$MEMORY_DETAILS\",
  \"memory\": {
    \"total\": $MEM_TOTAL,
    \"used\": $MEM_USED,
    \"percent\": $MEM_PERCENT,
  },
  \"disk\": [ $DISKS ],
  \"disk_total\": \"$DISK_TOTAL\",
  \"motherboard\": \"$MOTHERBOARD\",
  \"bios_version\": \"$BIOS_VERSION\",
  \"load\": $LOAD_AVG,
  \"top5\": [ $TOP5 ],
  \"online\": true
}"